﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Model;
using System.Data;
using System.Text;
using NBear.Mapping;
using KingRoad.EPM.Web.Util;
//using KingRoad.EPM.InvestmeEntity;
using DotNet.Service;
using DotNet.Model.MyEntity;
using KingRoad.EPM.Web.ViewModels;


namespace KingRoad.EPM.Web.Areas.Permission.Controllers
{
    /// <summary>
    /// 角色管理
    /// 功能描述：角色的增、删、改、查，与二次授权、关联用户、分配操作权限等等
    /// 模块负责人：张雨
    /// 完成日期：2011.9.23
    /// </summary>
    public class RoleController : Controller
    {
        //
        // GET: /Permission/Role/
        /// <summary>
        /// 角色管理首页加载
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 角色的添加指向
        /// </summary>
        /// <returns></returns>
        public ActionResult AddRole()
        {

            return View();
        }

        /// <summary>
        /// 角色的添加操作
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoleAdded(Base_Role entity)
        {
            int state = 1;//添加全局状态
            string addedID = string.Empty;//递增ID
            string outCode = string.Empty, outMessage = string.Empty;//返回状态码，状态信息
            if (ModelState.IsValid)
                addedID = ServiceManager.Instance.RoleService.AddRole(entity, out outCode, out outMessage);

            if (outCode.ToLower() == "okadd")
            {
                state = 0;
                //WS 2011.11.19 添加权限
                if (!UserService.CurrUserInfo.IsAdministrator)
                {
                    string stateP = string.Empty;
                    string msgP = string.Empty;
                    int curRoleID = ServiceManager.Instance.RoleService.GetRoleID();
                    if (curRoleID != 0)
                        ServiceManager.Instance.RoleService.GrantRoleRoleScopes(curRoleID.ToString(), addedID, out stateP, out msgP);
                }
            }

            return Json(new CallbackStatus
            {
                message = outMessage,
                statusCode = state == 0 ? "200" : "300",
                callbackType = "closeCurrent"
            });
        }
        //
        // GET: /Permission/Role/Edit/5
        /// <summary>
        /// 角色的编辑页加载
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns>实体</returns>
        public ActionResult roleEdit(string id)
        {
            Base_Role entity = ServiceManager.Instance.RoleService.GetRoleEntityByID(id);
            return View(entity);
        }

        //
        // POST: /Permission/Role/Edit/5
        /// <summary>
        /// 角色的编辑操作
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult roleEdited(BaseRoleEntity entity)
        {
            string outCode = string.Empty, outMessage = string.Empty;//返回状态码，返回信息
            Base_Role entitytemp = ServiceManager.Instance.RoleService.GetRoleEntityByID(Convert.ToString(entity.Id));
            entitytemp.Realname = entity.RealName;
            entitytemp.Enabled = Convert.ToInt32(entity.Enabled);
            entitytemp.Description = entity.Description;
            entitytemp.Code = entity.Code;
            ServiceManager.Instance.RoleService.UpdateRole(entitytemp, out outCode, out outMessage);
            return Json(new CallbackStatus
            {
                message = outMessage,
                statusCode = outCode.ToLower() == "okupdate" ? "200" : "300",
                callbackType = "closeCurrent"
            });
        }

        //
        // POST: /Permission/Role/Delete/5

        /// <summary>
        /// 对角色实现批量删除操作
        /// </summary>
        /// <returns></returns>
        public ActionResult Delete()
        {
            //TODO：以后要改，不允许批量删除！ WS 2011.11.19
            int state = 1;
            string RoleArryID = Request.Form["RoleArryID"];
            if (!string.IsNullOrEmpty(RoleArryID))
            {
                if (RoleArryID.LastIndexOf(',') == RoleArryID.Length - 1)
                {
                    RoleArryID = RoleArryID.Substring(0, RoleArryID.Length - 1);
                }
                if (ServiceManager.Instance.RoleService.BatchDelete(RoleArryID) > 0)
                {
                    state = 0;
                    //WS 2011.11.19去除权限
                    if (!UserService.CurrUserInfo.IsAdministrator)
                    {
                        string stateP = string.Empty;
                        string msgP = string.Empty;
                        int curRoleID = ServiceManager.Instance.RoleService.GetRoleID();
                        if (curRoleID != 0)
                            ServiceManager.Instance.RoleService.GrantRoleOrganizeScopes(curRoleID.ToString(), RoleArryID, out stateP, out msgP);
                    }
                }
            }

            return Json(new CallbackStatus
            {
                message = state == 0 ? "操作成功！" : "操作失败",
                statusCode = state == 0 ? "200" : "300",
                callbackType = "closeCurrent"
            });
            //return Json(state);
        }

        /// <summary>
        /// 获得所有的角色
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllRole(QueryBase query)
        {
            List<Base_Role> list = ServiceManager.Instance.RoleService.GetDT();

            var jqGridData = WebUtility.TojqGridData<Base_Role>(list, query);

            return Json(jqGridData);
        }

        /// <summary>
        /// 角色授权范围
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult roleSelect(string id)
        {
            Base_Role role = ServiceManager.Instance.RoleService.GetRoleEntityByID(id);

            //定义变量
            string tempType = "300", tempRole = string.Empty, tempOrganize = string.Empty, tempModule = string.Empty, tempPermissionitem = string.Empty;
            string tempRoleID = id;//获取角色ID
            if (!string.IsNullOrEmpty(tempRoleID))
            {
                //获取角色
                string[] templistrole = ServiceManager.Instance.RoleService.GetRoleIDsByRoleId(tempRoleID);
                tempRole = listToString(templistrole);
                //获取组织机构
                string[] tempOrganizes = ServiceManager.Instance.RoleService.GetRoleScopeOrganizeIds(tempRoleID);
                for (int i = 0; i < tempOrganizes.Length; i++)
                {
                    tempOrganize += "C_" + tempOrganizes[i];
                    if (i != (tempOrganizes.Length - 1))
                        tempOrganize += ",";
                }

                ////获取菜单模块，转化成字符串
                //string[] tempList = ServiceManager.Instance.RoleService.GetRoleScopeModuleIds(tempRoleID);
                //tempModule = listToString(tempList);

                ////获取操作权限集合，转化成字符串
                //string[] tempArry = ServiceManager.Instance.RoleService.GetRoleScopePermissionIds(tempRoleID);
                //tempPermissionitem = listToString(tempArry);
                tempType = "200";
            }
            //--转化成JSON格式输出
            //return Json(new KingRoad.EPM.InvestmeEntity.LoadValue(tempType, tempRole, tempOrganize, tempModule, tempPermissionitem));
            ViewBag.tempType = tempType;
            ViewBag.tempRole = tempRole;
            ViewBag.tempOrganize = tempOrganize;
            //ViewBag.tempModule = tempModule;
            //ViewBag.tempPermissionitem = tempPermissionitem;
            return View(role);
        }

        /// <summary>
        /// 创建用户时选择默认角色 WS 2011.11.29
        /// </summary>
        /// <param name="id">用户账号</param>
        /// <returns></returns>
        public ActionResult SelectRole(string id)
        {
            if (!String.IsNullOrEmpty(id)&&id != "0")
            {
                Base_User detailUser = ServiceManager.Instance.UserService.GetDTByUserName(id);
                if (detailUser != null)
                {
                    ViewBag.userID = detailUser.Id;
                    ViewBag.userName = id;
                    string[] roleListIDs = ServiceManager.Instance.UserService.GetUserRoleIds(detailUser.Id.ToString());
                    string roleListID = listToString(roleListIDs);//角色ID列表
                    ViewData["roleListID"] = roleListID;
                }
            }
            return View();
        }

        /// <summary>
        /// 获取数据做为Ztree的数据源
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRoleByzTree(string id)
        {
            List<Base_Role> list = ServiceManager.Instance.RoleService.GetDT();
            if (list != null)
            {
                list.ForEach(x =>
                    {
                        if (x.Id.ToString() == id)
                        {
                            x.Checked = true;
                        }
                    });
            }
            return Json(list);
        }

        /// <summary>
        /// 为页面加载后给当前角色模块及操作权限赋值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetLoadValue()
        {
            //定义变量
            string tempType = "300", tempRole = string.Empty, tempOrganize = string.Empty, tempModule = string.Empty, tempPermissionitem = string.Empty;
            string tempRoleID = Request.Params["roleID"];//获取角色ID
            if (!string.IsNullOrEmpty(tempRoleID))
            {
                //获取角色
                string[] templistrole = ServiceManager.Instance.RoleService.GetRoleIDsByRoleId(tempRoleID);
                tempRole = listToString(templistrole);
                //获取组织机构
                string[] tempOrganizes = ServiceManager.Instance.RoleService.GetRoleScopeOrganizeIds(tempRoleID);
                for (int i = 0; i < tempOrganizes.Length; i++)
                {
                    tempOrganize += "C_" + tempOrganizes[i];
                    if (i != (tempOrganizes.Length - 1))
                        tempOrganize += ",";
                }

                //获取菜单模块，转化成字符串
                string[] tempList = ServiceManager.Instance.RoleService.GetRoleScopeModuleIds(tempRoleID);
                tempModule = listToString(tempList);

                //获取操作权限集合，转化成字符串
                string[] tempArry = ServiceManager.Instance.RoleService.GetRoleScopePermissionIds(tempRoleID);
                tempPermissionitem = listToString(tempArry);
                tempType = "200";
            }
            //转化成JSON格式输出
            return null;//Json(new LoadValue(tempType, tempRole, tempOrganize, tempModule, tempPermissionitem));
        }

        /// <summary>
        /// 将数组转化成字符串以指定字符分隔
        /// </summary>
        /// <param name="arry"></param>
        /// <returns></returns>
        private string listToString(string[] arry)
        {
            if (arry == null || arry.Length == 0)
                return string.Empty;
            string s = ",";
            string str = string.Empty;
            for (int i = 0; i < arry.Length; i++)
            {
                str += arry[i];
                if (i != (arry.Length - 1))
                    str += s;
            }
            return str;
        }

        /// <summary>
        /// 取得用户数据做为zTree的数据源
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUserByzTree()
        {
            DataTable user = ServiceManager.Instance.RoleService.GetDTUser();

            List<Base_User> list = new List<Base_User>();

            ObjectMapper mapper = new ObjectMapper(typeof(DataRow), typeof(Base_User));

            foreach (DataRow dr in user.Rows)
            {
                Base_User tempUser = mapper.ConvertObject(dr) as Base_User;
                list.Add(tempUser);
            }
            return Json(list);
        }

        /// <summary>
        /// 为角色授权的方法
        /// WS 2010.10.25 进行全面修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetRoleSelect()
        {
            string state = "300", Message = "角色授权失败！";
            //定义变量
            string roleID = string.Empty, rListID = string.Empty, oListID = string.Empty, mListID = string.Empty, pListID = string.Empty;
            roleID = Request.Params["roleID"];
            if (!string.IsNullOrEmpty(roleID))
            {
                //获取参数
                if (!String.IsNullOrEmpty(Request["rListID"]))
                    rListID = Request["rListID"];
                if (!String.IsNullOrEmpty(Request["oListID"]))
                    oListID = Request["oListID"];
                if (!String.IsNullOrEmpty(Request["mListID"]))
                    mListID = Request["mListID"];
                if (!String.IsNullOrEmpty(Request["pListID"]))
                    pListID = Request["pListID"];

                string templist = string.Empty;//定义一个全局变量

                #region 操作角色权限,先获取以前的角色权限
                string[] oldRoleList = ServiceManager.Instance.RoleService.GetRoleIDsByRoleId(roleID);
                //全删全添
                if (oldRoleList != null && oldRoleList.Length > 0)
                {
                    ServiceManager.Instance.RoleService.RevokeRoleRoleScopes(roleID, listToString(oldRoleList), out state, out Message);
                }
                if (!String.IsNullOrEmpty(rListID))
                {
                    if (rListID.EndsWith(","))
                        rListID = rListID.Substring(0, rListID.Length - 1);
                    ServiceManager.Instance.RoleService.GrantRoleRoleScopes(roleID, rListID, out state, out Message);
                }
                #region 原来张雨写的代码
                ////验证如果原始权限没有   当前权限有 则添加
                //if (oldRoleList == null || oldRoleList.Length == 0 && rListID != null)
                //{
                //    ServiceManager.Instance.RoleService.GrantRoleRoleScopes(roleID, rListID, out state, out Message);
                //}
                //else if (oldRoleList != null && oldRoleList.Length > 0 && rListID == null)//如果当前权限没有 原始权限有 则移除
                //{
                //    ServiceManager.Instance.RoleService.RevokeRoleRoleScopes(roleID, listToString(oldRoleList), out state, out Message);
                //}
                //else
                //{
                //    string[] listrListID = rListID.Split(',');
                //    templist = string.Empty;
                //    //以原始权限为参照，比对当前权限  若当前权限没有则移除
                //    for (int i = 0; i < oldRoleList.Length; i++)
                //    {
                //        if (!listrListID.Contains(oldRoleList[i]))
                //        {
                //            templist += oldRoleList[i] + ",";//记录需要移除的角色
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.RevokeRoleRoleScopes(roleID, templist, out state, out Message);
                //    }

                //    templist = string.Empty;//清空记录器
                //    //以当前权限为参照，比对原始权限   若原始权限没有的则添加
                //    for (int i = 0; i < listrListID.Length; i++)
                //    {
                //        if (!oldRoleList.Contains(listrListID[i]))
                //        {
                //            templist += listrListID[i] + ",";//记录需要添加的角色
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.GrantRoleRoleScopes(roleID, templist, out state, out Message);
                //    }
                //}
                #endregion
                #endregion

                #region 操作组织机构,先获取以前的组织机构
                string[] oldOrganizeList = ServiceManager.Instance.RoleService.GetRoleScopeOrganizeIds(roleID);
                //全删全添
                if (oldOrganizeList != null && oldOrganizeList.Length > 0)
                {
                    ServiceManager.Instance.RoleService.RevokeRoleOrganizeScopes(roleID, listToString(oldOrganizeList), out state, out Message);
                }
                if (!String.IsNullOrEmpty(oListID))
                {
                    if (oListID.EndsWith(","))
                        oListID = oListID.Substring(0, oListID.Length - 1);
                    //由于构造组织机构树带有前缀，需要先去除
                    string reOListID = String.Empty;
                    for (int i = 0; i < oListID.Split(',').Length; i++)
                    {
                        reOListID += oListID.Split(',')[i].Substring(2);
                        if (i != (oListID.Split(',').Length - 1))
                            reOListID += ",";
                    }

                    ServiceManager.Instance.RoleService.GrantRoleOrganizeScopes(roleID, reOListID, out state, out Message);
                }

                #region 原来章鱼写的代码
                //if (oldOrganizeList == null || oldOrganizeList.Length == 0 && oListID != null)
                //{
                //    ServiceManager.Instance.RoleService.GrantRoleOrganizeScopes(roleID, oListID, out state, out Message);
                //}
                //else if (oldOrganizeList != null && oldOrganizeList.Length > 0 && oListID == null)//如果当前权限没有 原始权限有 则移除
                //{
                //    ServiceManager.Instance.RoleService.RevokeRoleOrganizeScopes(roleID, listToString(oldOrganizeList), out state, out Message);
                //}
                //else
                //{
                //    string[] listoListID = oListID.Split(',');
                //    templist = string.Empty;
                //    //以原始权限为参照，比对当前权限  若当前权限没有则移除
                //    for (int i = 0; i < oldOrganizeList.Length; i++)
                //    {
                //        if (!listoListID.Contains(oldOrganizeList[i]))
                //        {
                //            templist += oldOrganizeList[i] + ",";//记录需要移除的组织机构
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.RevokeRoleOrganizeScopes(roleID, templist, out state, out Message);
                //    }

                //    templist = string.Empty;//清空记录器
                //    //以当前权限为参照，比对原始权限   若原始权限没有的则添加
                //    for (int i = 0; i < listoListID.Length; i++)
                //    {
                //        if (!oldOrganizeList.Contains(listoListID[i]))
                //        {
                //            templist += listoListID[i] + ",";//记录需要添加的组织机构
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.GrantRoleOrganizeScopes(roleID, templist, out state, out Message);
                //    }
                //}
                #endregion
                #endregion

                #region 操作模块菜单,先获取以前的模块菜单
                //string[] oldmoduleList = ServiceManager.Instance.RoleService.GetRoleScopeModuleIds(roleID);
                ////全删全添
                //if (oldmoduleList != null && oldmoduleList.Length > 0)
                //{
                //    ServiceManager.Instance.RoleService.RevokeRoleModuleScopes(roleID, listToString(oldmoduleList), out state, out Message);
                //}
                //if (!String.IsNullOrEmpty(mListID))
                //{
                //    if (mListID.EndsWith(","))
                //        mListID = mListID.Substring(0, mListID.Length - 1);
                //    ServiceManager.Instance.RoleService.GrantRoleModuleScopes(roleID, mListID, out state, out Message);
                //}

                #region 原来张雨写的代码
                //if (oldmoduleList != null && oldmoduleList.Length > 0)
                //{
                //    ServiceManager.Instance.RoleService.RevokeRoleModuleScopes(roleID, listToString(oldmoduleList), out state, out Message);
                //}
                //if (!String.IsNullOrEmpty(mListID))
                //{
                //    if (mListID.EndsWith(","))
                //        mListID.Substring(0, mListID.Length - 1);
                //    ServiceManager.Instance.RoleService.GrantRoleModuleScopes(roleID, mListID, out state, out Message);
                //}

                //if (oldmoduleList == null || oldmoduleList.Length == 0 && mListID != null)
                //{
                //    ServiceManager.Instance.RoleService.GrantRoleModuleScopes(roleID, mListID, out state, out Message);
                //}
                //else if (oldmoduleList != null && oldmoduleList.Length > 0 && mListID == null)//如果当前权限没有 原始权限有 则移除
                //{
                //    ServiceManager.Instance.RoleService.RevokeRoleModuleScopes(roleID, listToString(oldmoduleList), out state, out Message);
                //}
                //else
                //{
                //    string[] listmListID = mListID.Split(',');
                //    templist = string.Empty;
                //    //以原始权限为参照，比对当前权限  若当前权限没有则移除
                //    for (int i = 0; i < oldmoduleList.Length; i++)
                //    {
                //        if (!listmListID.Contains(oldmoduleList[i]))
                //        {
                //            templist += oldmoduleList[i] + ",";//记录需要移除的模块菜单
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.RevokeRoleModuleScopes(roleID, templist, out state, out Message);
                //    }

                //    templist = string.Empty;//清空记录器
                //    //以当前权限为参照，比对原始权限   若原始权限没有的则添加
                //    for (int i = 0; i < listmListID.Length; i++)
                //    {
                //        if (!oldmoduleList.Contains(listmListID[i]))
                //        {
                //            templist += listmListID[i] + ",";//记录需要添加的模块菜单
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.GrantRoleModuleScopes(roleID, templist, out state, out Message);
                //    }
                //}
                #endregion
                #endregion

                #region 操作操作权限,先获取以前的操作权限
                //string[] oldPermissionitem = ServiceManager.Instance.RoleService.GetRoleScopePermissionIds(roleID);
                ////全删全添
                //if (oldPermissionitem != null && oldPermissionitem.Length > 0)
                //{
                //    ServiceManager.Instance.RoleService.RevokeRolePermissionItemScopes(roleID, listToString(oldPermissionitem), out state, out Message);
                //}
                //if (!String.IsNullOrEmpty(pListID))
                //{
                //    if (pListID.EndsWith(","))
                //        pListID = pListID.Substring(0, pListID.Length - 1);
                //    ServiceManager.Instance.RoleService.GrantRolePermissionItemScopes(roleID, pListID, out state, out Message);
                //}

                #region 原来张雨写的代码
                //if (oldPermissionitem == null || oldPermissionitem.Length == 0 && pListID != null)
                //{
                //    ServiceManager.Instance.RoleService.GrantRolePermissionItemScopes(roleID, pListID, out state, out Message);
                //}
                //else if (oldPermissionitem != null && oldPermissionitem.Length > 0 && pListID == null)//如果当前权限没有 原始权限有 则移除
                //{
                //    ServiceManager.Instance.RoleService.RevokeRolePermissionItemScopes(roleID, listToString(oldPermissionitem), out state, out Message);
                //}
                //else
                //{
                //    string[] listpListID = pListID.Split(',');
                //    templist = string.Empty;
                //    //以原始权限为参照，比对当前权限  若当前权限没有则移除
                //    for (int i = 0; i < oldPermissionitem.Length; i++)
                //    {
                //        if (!listpListID.Contains(oldPermissionitem[i]))
                //        {
                //            templist += oldPermissionitem[i] + ",";//记录需要移除的操作权限
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.RevokeRolePermissionItemScopes(roleID, templist, out state, out Message);
                //    }

                //    templist = string.Empty;//清空记录器
                //    //以当前权限为参照，比对原始权限   若原始权限没有的则添加
                //    for (int i = 0; i < listpListID.Length; i++)
                //    {
                //        if (!oldPermissionitem.Contains(listpListID[i]))
                //        {
                //            templist += listpListID[i] + ",";//记录需要添加的操作权限
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.GrantRolePermissionItemScopes(roleID, templist, out state, out Message);
                //    }
                //}
                #endregion
                #endregion

            }
            else
            {
                state = "300";
                Message = "角色授权失败！";
            }
            return Json(new CallbackStatus
            {
                message = Message,
                statusCode = state,
                callbackType = "closeCurrent"
            });
        }

        /// <summary>
        /// 角色用户关联页面
        /// </summary>
        /// <returns></returns>
        public ActionResult LinkUser(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                ViewBag.roleID = string.Empty;
            }
            else
            {
                Base_Role role = ServiceManager.Instance.RoleService.GetRoleEntityByID(id);
                ViewBag.roleID = id;
                ViewBag.roleName = role.Realname;
                ViewData["UserByRole"] = listToString(ServiceManager.Instance.RoleService.GetRoleUserIds(id));
            }
            return View();
        }

        /// <summary>
        /// 设置角色用户关联
        /// </summary>
        /// <returns></returns>
        public ActionResult SetLinkUser()
        {
            string state = "300", message = "角色用户关联失败！";
            //全局参数
            string roleID = string.Empty, userListID = string.Empty;
            roleID = Request.Params["roleID"];
            if (!string.IsNullOrEmpty(roleID))
            {
                userListID = Request.Params["userIDs"];
                if (userListID == null)
                    userListID = string.Empty;
                if (userListID.EndsWith(","))
                    userListID = userListID.Substring(0, userListID.Length - 1);
                string[] userlist = ServiceManager.Instance.RoleService.GetRoleUserIds(roleID);//获取该角色下的所有用户                
                if (userlist == null || userlist.Length == 0 && userListID != string.Empty)
                {
                    ServiceManager.Instance.RoleService.AddUserRole(roleID, userListID);
                }
                else if (userListID == string.Empty && userlist.Length > 0)
                {
                    ServiceManager.Instance.RoleService.RemoveUserFromRole(roleID, listToString(userlist));
                }
                else if (userListID == string.Empty && userlist.Length == 0)
                {
                    state = "200";
                    message = "角色用户关联成功";
                }
                else
                {
                    string templist = string.Empty;
                    string[] tempUserList = userListID.Split(',');
                    //以原用户为参照，比对现有用户
                    for (int i = 0; i < tempUserList.Length; i++)
                    {
                        if (!userlist.Contains(tempUserList[i]))
                        {
                            templist += tempUserList[i] + ",";
                        }
                    }
                    if (templist.EndsWith(","))
                        templist = templist.Substring(0, templist.Length - 1);
                    //将新增的用户添加到角色中去
                    if (templist != string.Empty)
                        ServiceManager.Instance.RoleService.AddUserRole(roleID, templist);

                    templist = string.Empty;

                    for (int i = 0; i < userlist.Length; i++)
                    {
                        if (!tempUserList.Contains(userlist[i]))
                        {
                            templist += userlist[i] + ",";
                        }
                    }
                    //移除取消的用户
                    if (templist != string.Empty)
                        ServiceManager.Instance.RoleService.RemoveUserFromRole(roleID, templist);
                }
                state = "200";
                message = "角色用户关联成功！";
            }
            return Json(new CallbackStatus
            {
                message = message,
                statusCode = state,
                callbackType = "closeCurrent"
            });
        }
        
        /// <summary>
        /// 分配菜单权限操作
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectModule(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                ViewBag.roleID = string.Empty;
            }
            else
            {
                ViewBag.roleID = id;
                ViewBag.roleName = ServiceManager.Instance.RoleService.GetRoleEntityByID(id).Realname;
                ViewData["moduleListID"] = listToString(ServiceManager.Instance.RoleService.GetRoleAccessModuleIds(id));
            }
            return View();
        }
        public ActionResult GetPermissionItems() 
        {
            List<Base_Module> list = ServiceManager.Instance.PermissionService.GetlistPermissionTree() as List<Base_Module>;
            return Json(list);
        }
        /// <summary>
        /// 给角色授权菜单模块访问权限
        /// </summary>
        /// <returns></returns>
        public ActionResult SetSelectModule()
        {
            string state = "300", Message = "角色授权失败！";
            string roleID = Request.Params["roleID"];
            if (!string.IsNullOrEmpty(roleID))
            {
                string[] oldListModule = ServiceManager.Instance.RoleService.GetRoleAccessModuleIds(roleID);
                string ModuleIDs = Request.Params["moduleIDs"];
                if (ModuleIDs == null)
                    ModuleIDs = string.Empty;
                if (ModuleIDs.EndsWith(","))
                    ModuleIDs = ModuleIDs.Substring(0, ModuleIDs.Length - 1);
                //WS 全删全添 2010.11.1
                if (oldListModule != null && oldListModule.Length > 0)
                {
                        ServiceManager.Instance.RoleService.RevokeRoleVisitModuleScope(roleID, listToString(oldListModule), out state, out Message);
                }
                if (ModuleIDs != null)
                {
                    if (ModuleIDs.EndsWith(","))
                        ModuleIDs = ModuleIDs.Substring(0, ModuleIDs.Length - 1);
                    ServiceManager.Instance.RoleService.GrantRoleVisitModuleScope(roleID, ModuleIDs, out state, out Message);
                }

                #region 原来张雨的代码
                //if (oldListModule == null || oldListModule.Length == 0 && ModuleIDs != null)
                //{
                //    ServiceManager.Instance.RoleService.GrantRoleVisitModuleScope(roleID, ModuleIDs, out state, out Message);
                //}
                //else if (oldListModule != null && oldListModule.Length > 0 && ModuleIDs == null)//如果当前权限没有 原始权限有 则移除
                //{
                //    ServiceManager.Instance.RoleService.RevokeRoleVisitModuleScope(roleID, listToString(oldListModule), out state, out Message);
                //}
                //else
                //{
                //    string[] listmListID = ModuleIDs.Split(',');
                //    string templist = string.Empty;
                //    //以原始权限为参照，比对当前权限  若当前权限没有则移除
                //    for (int i = 0; i < listmListID.Length; i++)
                //    {
                //        if (!oldListModule.Contains(listmListID[i]))
                //        {
                //            templist += listmListID[i] + ",";//记录需要添加的模块菜单
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.GrantRoleVisitModuleScope(roleID, templist, out state, out Message);
                //    }
                //    templist = string.Empty;//清空记录器
                //    //以当前权限为参照，比对原始权限   若原始权限没有的则添加
                //    for (int i = 0; i < oldListModule.Length; i++)
                //    {
                //        if (!listmListID.Contains(oldListModule[i]))
                //        {
                //            templist += oldListModule[i] + ",";//记录需要移除的模块菜单
                //        }
                //    }
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.RevokeRoleVisitModuleScope(roleID, templist, out state, out Message);
                //    }
                //}
                #endregion
            }
            return Json(new CallbackStatus
            {
                message = Message,
                statusCode = state,
                callbackType = "closeCurrent"
            });
        }

        /// <summary>
        /// 关联操作权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SelectPermission(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                ViewBag.roleID = string.Empty;
            }
            else
            {
                ViewBag.roleID = id;
                ViewBag.roleName = ServiceManager.Instance.RoleService.GetRoleEntityByID(id).Realname;
                ViewData["PermissionIDs"] = listToString(ServiceManager.Instance.RoleService.GetRolePermissionIds(id));
            }
            return View();
        }

        /// <summary>
        /// 给角色授权操作权限
        /// </summary>
        /// <returns></returns>
        public ActionResult SetSelectPermiss()
        {
            string state = "300", Message = "操作权限授权失败！";
            string roleID = Request.Params["roleID"];
            if (!string.IsNullOrEmpty(roleID))
            {
                string[] oldListPermission = ServiceManager.Instance.RoleService.GetRolePermissionIds(roleID);
                string PermissionIDs = Request.Params["permissIDs"];
                if (PermissionIDs == null)
                    PermissionIDs = string.Empty;
                if (PermissionIDs.EndsWith(","))
                    PermissionIDs = PermissionIDs.Substring(0, PermissionIDs.Length - 1);
                #region 更改过后的
                ServiceManager.Instance.RoleService.RevokeRolePermissions(roleID, listToString(oldListPermission), out state, out Message);
                ServiceManager.Instance.RoleService.GrantRolePermissions(roleID, PermissionIDs, out state, out Message);
                #endregion

                #region 原来写的
                //if (oldListPermission == null || oldListPermission.Length == 0 && PermissionIDs != null)
                //{
                //    ServiceManager.Instance.RoleService.GrantRolePermissions(roleID, PermissionIDs, out state, out Message);
                //}
                //else if (oldListPermission != null && oldListPermission.Length > 0 && PermissionIDs == null)//如果当前权限没有 原始权限有 则移除
                //{
                //    ServiceManager.Instance.RoleService.RevokeRolePermissions(roleID, listToString(oldListPermission), out state, out Message);
                //}
                //else
                //{
                //    string[] listpListID = PermissionIDs.Split(',');
                //    string templist = string.Empty;
                //    //以原始权限为参照，比对当前权限  若当前权限没有则移除
                //    for (int i = 0; i < listpListID.Length; i++)
                //    {
                //        if (!oldListPermission.Contains(listpListID[i]))
                //        {
                //            templist += listpListID[i] + ",";//记录需要添加的模块菜单
                //        }
                //    }
                //    if (templist.EndsWith(","))
                //        templist = templist.Substring(0, templist.Length - 1);
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.GrantRolePermissions(roleID, templist, out state, out Message);
                //    }
                //    templist = string.Empty;//清空记录器
                //    //以当前权限为参照，比对原始权限   若原始权限没有的则添加
                //    for (int i = 0; i < oldListPermission.Length; i++)
                //    {
                //        if (!listpListID.Contains(oldListPermission[i]))
                //        {
                //            templist += oldListPermission[i] + ",";//记录需要移除的模块菜单
                //        }
                //    }
                //    if (templist.EndsWith(","))
                //        templist = templist.Substring(0, templist.Length - 1);
                //    if (templist != string.Empty)
                //    {
                //        ServiceManager.Instance.RoleService.RevokeRolePermissions(roleID, templist, out state, out Message);
                //    }
                //}
                #endregion

            }
            return Json(new CallbackStatus
            {
                message = Message,
                statusCode = state,
                callbackType = "closeCurrent"
            });
        }
    }
}
